package com.lsj.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lsj.common.utils.HttpUtils;
import com.lsj.common.utils.R;
import com.lsj.gulimall.auth.feign.MemberFeignService;
import com.lsj.gulimall.auth.vo.GiteeSocialUser;
import com.lsj.gulimall.auth.vo.MemberEntityVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 梁胜君
 * @version 1.0
 * @create 2022/12/30 20:51
 */
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("oauth2.0/gitee/success")
    public String gitee(String code,String error,String error_description) throws Exception {
        if (error != null && error_description != null) {
            return "redirect:http://shengjunauth.com/login.html";
        }
        if (code != null) {
            // 获取gitee平台的access_token
            Map<String,String> map = new HashMap<>();
            map.put("grant_type","authorization_code");
            map.put("code",code);
            map.put("client_id","a04791d4fbfaf433062cf71e974adba323d87fa3d6ec97056c1c08ee75b9ffda");
            map.put("redirect_uri","http://shengjunauth.com/oauth2.0/gitee/success");
            map.put("client_secret","970c01f331bc03619f071fecdfdce88e8d64493d9d9edd2f8b3d2d662fdb1e48");

            HttpResponse httpResponse = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                String json = EntityUtils.toString(entity);
                GiteeSocialUser socialUser = JSON.parseObject(json, GiteeSocialUser.class);
                System.out.println(socialUser);
                R r = memberFeignService.socialLogin(socialUser);
                if (r.getCode() == 0) {
                    MemberEntityVo memberEntityVo = r.getData("data",new TypeReference<MemberEntityVo>(){});
                    System.out.println(memberEntityVo);
                    return "redirect:http://shengjunmall.com";
                }
            }
        } else {
            return "redirect:http://shengjunauth.com/login.html";
        }

        return "redirect:http://shengjunauth.com/login.html";
    }

}
